<script setup>
import { onMounted, reactive } from "vue";
import { useMessage } from "naive-ui";
import TheIcon from "@/components/icon/TheIcon.vue";
import api from "@/api";
import { getToken } from "@/utils";

const base_path = import.meta.env.VITE_BASE

const message = useMessage()

const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(["call-parent"]) 

const record = reactive({
  file_number: "",
  arrival_time: null, // yyyy-MM-dd HH:mm:ss
  patient_name: "",
  height: "",
  weight: "",
  temperature: "",
  blood_pressure: "",
  pulse: "",
  chief_complaint: "",

  sexual_activity_frequency: "",
  sexual_activity_description: [],
  pelvic_muscle_function: [],
  perimenopausal_symptoms: [],
  past_gynecological_exam_history: "",
  reproductive_anti_aging_treatment_history: "否",

  menarche_age: "",
  last_menstrual_period_date: null, // yyyy-MM-dd
  menstrual_cycle_duration: "",
  menstrual_flow: "",
  single_menstrual_cycle_days: "",
  dysmenorrhea_condition: "",
  blood_clot_condition: "",

  marriage_obstetric_history: "",
  is_pregnant: 0,
  first_pregnancy_age: "",
  first_childbirth_age: "",
  vaginal_delivery_count: 0,
  cesarean_section_count: 0,
  induced_abortion_count: 0,
  premature_birth_count: 0,
  last_pregnancy_age: "",
  last_childbirth_age: "",
  is_preparing_pregnancy: 0,
  is_breastfeeding: 0,
  contraception_method: "",
  marital_status: "",
  marriage_age: "",
  pregnant_time: "",
  delivery_time: "",
  alcohol_consumption: "",
  sleep_condition: "",
  smoking_condition: "",
  diet_habit: [],
  bowel_movement_condition: "",
  exercise_frequency: "",
  exercise_methods: [],

  past_medical_history: "",
  past_surgical_history: "",
  allergy_history: "",
  allergic_drugs: "",
  family_medical_history: [],
  files: [],

  // local ui state
  is_edit: false
})

// 上传相关本地状态（新上传未保存的文件）
const uploadState = reactive({
  uploadAction: base_path + '/system/base/userimg',
  token: getToken(),
  files: []
})

onMounted(() => {
  if(!record.arrival_time){
    record.arrival_time = formatDateTimeSafe(new Date())
  }
  if(!props.infoData.user_id){
    edit_info()
  }else{
    on_ref()
  }
})

function formatDateTimeSafe(d) {
  if (!d) return null
  try {
    if (typeof d === "string") return d
    const dt = new Date(d)
    if (isNaN(dt.getTime())) return null
    const pad = (n) => String(n).padStart(2, "0")
    return `${dt.getFullYear()}-${pad(dt.getMonth()+1)}-${pad(dt.getDate())} ${pad(dt.getHours())}:${pad(dt.getMinutes())}:${pad(dt.getSeconds())}`
  } catch { return null }
}

function save_info() {
  const payload = { ...record }
  payload.user_id = props.infoData.id
  payload.arrival_time = formatDateTimeSafe(payload.arrival_time)
  if (payload.last_menstrual_period_date instanceof Date) {
    const d = payload.last_menstrual_period_date
    const pad = (n) => String(n).padStart(2, "0")
    payload.last_menstrual_period_date = `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`
  }
  // 合并已保存与新上传的文件
  let allFiles = []
  if (Array.isArray(record.files) && record.files.length > 0) {
    allFiles = [...record.files]
  }
  if (Array.isArray(uploadState.files) && uploadState.files.length > 0) {
    const newFiles = uploadState.files.map(item => {
      if (item.url) return item.url
      if (item.response?.data?.url) return item.response.data.url
      return null
    }).filter(Boolean)
    allFiles = [...allFiles, ...newFiles]
  }
  payload.files = allFiles
  api.updateHealthRecord(payload).then(() => {
    message.success('编辑成功')
    emit('call-parent')
    cancel_info()
    on_ref()
  })
}

function on_ref(){
  update_info()
}

function edit_info(){
  if(!record.arrival_time){
    record.arrival_time = formatDateTimeSafe(new Date())
  }
  record.is_edit = true
}

function cancel_info(){
  record.is_edit = false
  // 清空未保存的新上传文件
  uploadState.files = []
}

function update_info(){
  api.getHealthRecord({
    user_id: props.infoData.user_id
  }).then((res)=>{
    if(res.data){
      Object.assign(record, res.data)
      // normalize array fields
      record.sexual_activity_description ||= []
      record.pelvic_muscle_function ||= []
      record.perimenopausal_symptoms ||= []
      record.diet_habit ||= []
      record.exercise_methods ||= []
      record.family_medical_history ||= []
      record.files ||= []
    }
  })
}

// Options from images
const OPT = {
  sexualFreq: ["规律", "不规律", "绝经", "不详"],
  sexualDesc: ["性高潮", "性交痛", "阴道干涩", "阴吹", "性欲下降", "性敏感度低/性冷淡"],
  pelvic: ["压力性尿失禁", "子宫/阴道/膀胱脱垂", "其他"],
  peri: ["潮热", "面红", "盗汗", "易怒", "烦躁", "抑郁", "月经紊乱"],
  menstrual_cycle_duration:["规律", "不规律", "绝经", "不详"],
  menstrualFlow: ["少", "中等", "多"],
  dysmenorrhea: ["无", "轻微", "中度", "重度"],
  clot: ["无", "偶见", "明显"],
  yesNo: ["是", "否"],
  alcohol: ["不饮酒", "1-10次/月", "11-20次/月", "21-30次/月"],
  smoking: ["从不吸烟", "过去吸,现在已戒烟", "半包/天", "半包1包/天", ">1包/天", "不是每天吸"],
  diet: ["荤素均衡", "荤食为主", "素食为主", "嗜盐", "嗜油", "嗜糖", "其他"],
  toilet: ["频尿/排尿费力", "便秘/经常腹泻", "如厕正常"],
  exerciseFreq: ["不规律", "不运动", "每天", "5-6天/周", "3-4天/周", "1-2天/周", "少于1天/月", "1-3天/月"],
  exerciseMethods: ["快步走", "登山", "跑步", "其他"],
  family: [
    "高血压", "糖尿病", "脑中风", "冠心病或心肌梗塞", "高胆固醇/高血脂",
    "肾脏疾病", "肝硬化", "乙肝或丙肝", "骨质疏松", "痛风", "关节病变",
    "哮喘", "过敏", "甲状腺疾病", "阿尔兹海默症", "帕金森氏症", "脱发",
    "自身免疫性疾病", "良性或恶性肿瘤", "肠", "肝", "肺", "乳腺", "甲状腺",
    "前列腺", "胃", "其他疾病"
  ]
}

// 上传完成回调（写入 file.url 以便后续保存）
function handleFinish({ file, event }){
  let data = (event?.target)?.response
  try { data = JSON.parse(data) } catch (e) { data = null }
  if (data && data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data?.data || '上传失败')
  }
  return file
}

function getFileName(fileUrl){
  if(!fileUrl) return '未知文件'
  try{
    const u = new URL(fileUrl)
    return u.pathname.split('/').pop() || '未知文件'
  }catch{
    const parts = String(fileUrl).split('/')
    return parts[parts.length-1] || '未知文件'
  }
}

function downloadFile(fileUrl){
  if (!fileUrl) return message.error('文件链接无效')
  const a = document.createElement('a')
  a.href = fileUrl
  a.target = '_blank'
  a.download = getFileName(fileUrl)
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

function removeSavedFile(index){
  if (Array.isArray(record.files) && index > -1 && index < record.files.length) {
    record.files.splice(index, 1)
    message.success('文件已删除')
  }
}

function removeNewFile(index){
  if (Array.isArray(uploadState.files) && index > -1 && index < uploadState.files.length) {
    uploadState.files.splice(index, 1)
    message.success('文件已删除')
  }
}
</script>

<template>
  <NScrollbar style="position:relative;height:calc(100vh - 106px);padding-bottom: 60px">
    <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
      <template #header>
        <n-h6 prefix="bar" style="margin: 0;font-size: 18px">基础信息</n-h6>
      </template>
      <div class="info1">
        <n-descriptions style="width: 100%;" label-placement="left" bordered :column="4">
          <n-descriptions-item label="档案号">
            <span v-if="!record.is_edit">{{ record.file_number }}</span>
            <n-input v-else v-model:value="record.file_number"/>
          </n-descriptions-item>
          <n-descriptions-item label="到院时间">
            <span v-if="!record.is_edit">{{ record.arrival_time }}</span>
            <n-date-picker v-else v-model:value="record.arrival_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" clearable placeholder="到院时间"/>
          </n-descriptions-item>
          <n-descriptions-item label="姓名">
            <span v-if="!record.is_edit">{{ record.patient_name }}</span>
            <n-input v-else v-model:value="record.patient_name"/>
          </n-descriptions-item>
          <n-descriptions-item label="身高(cm)">
            <span v-if="!record.is_edit">{{ record.height }}</span>
            <n-input v-else v-model:value="record.height" placeholder="身高(cm)"/>
          </n-descriptions-item>
          <n-descriptions-item label="体重(kg)">
            <span v-if="!record.is_edit">{{ record.weight }}</span>
            <n-input v-else v-model:value="record.weight" placeholder="体重(kg)"/>
          </n-descriptions-item>
          <n-descriptions-item label="体温(°C)">
            <span v-if="!record.is_edit">{{ record.temperature }}</span>
            <n-input v-else v-model:value="record.temperature" placeholder="体温(°C)"/>
          </n-descriptions-item>
          <n-descriptions-item label="血压(mmHg)">
            <span v-if="!record.is_edit">{{ record.blood_pressure }}</span>
            <n-input v-else v-model:value="record.blood_pressure" placeholder="120/80"/>
          </n-descriptions-item>
          <n-descriptions-item label="脉搏(次/分)">
            <span v-if="!record.is_edit">{{ record.pulse }}</span>
            <n-input v-else v-model:value="record.pulse"/>
          </n-descriptions-item>
          <n-descriptions-item label="主诉(伴随症状)" :span="4">
            <span v-if="!record.is_edit">{{ record.chief_complaint }}</span>
            <n-input v-else type="textarea" :autosize="{minRows:3,maxRows:5}" v-model:value="record.chief_complaint"/>
          </n-descriptions-item>
        </n-descriptions>
      </div>
    </n-card>

    <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
      <template #header>
        <n-h6 prefix="bar" style="margin: 0;font-size: 18px">生殖系统情况</n-h6>
      </template>
      <div class="info1">
        <n-descriptions style="width: 100%;" label-placement="left" bordered :column="3">
          <n-descriptions-item label="性生活频率">
            <span v-if="!record.is_edit">{{ record.sexual_activity_frequency }}</span>
            <n-radio-group v-else v-model:value="record.sexual_activity_frequency">
              <n-space>
                <n-radio v-for="v in OPT.sexualFreq" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="性生活现状描述" :span="2">
            <span v-if="!record.is_edit">{{ record.sexual_activity_description?.join('、') }}</span>
            <n-checkbox-group v-else v-model:value="record.sexual_activity_description">
              <n-space>
                <n-checkbox v-for="v in OPT.sexualDesc" :key="v" :value="v">{{ v }}</n-checkbox>
              </n-space>
            </n-checkbox-group>
          </n-descriptions-item>
          <n-descriptions-item label="盆底肌功能">
            <span v-if="!record.is_edit">{{ record.pelvic_muscle_function?.join('、') }}</span>
            <n-checkbox-group v-else v-model:value="record.pelvic_muscle_function">
              <n-space>
                <n-checkbox v-for="v in OPT.pelvic" :key="v" :value="v">{{ v }}</n-checkbox>
              </n-space>
            </n-checkbox-group>
          </n-descriptions-item>
          <n-descriptions-item label="围绝经期症状" :span="2">
            <span v-if="!record.is_edit">{{ record.perimenopausal_symptoms?.join('、') }}</span>
            <n-checkbox-group v-else v-model:value="record.perimenopausal_symptoms">
              <n-space>
                <n-checkbox v-for="v in OPT.peri" :key="v" :value="v">{{ v }}</n-checkbox>
              </n-space>
            </n-checkbox-group>
          </n-descriptions-item>
          <n-descriptions-item label="既往妇科检查史" :span="3">
            <span v-if="!record.is_edit">{{ record.past_gynecological_exam_history }}</span>
            <n-input v-else type="textarea" :autosize="{minRows:2,maxRows:4}" v-model:value="record.past_gynecological_exam_history"/>
          </n-descriptions-item>
          <n-descriptions-item label="生殖抗衰治疗史 （是否做过生殖抗衰类治疗(含产后修复) ）">
            <span v-if="!record.is_edit">{{ record.reproductive_anti_aging_treatment_history }}</span>
            <n-radio-group v-else v-model:value="record.reproductive_anti_aging_treatment_history">
              <n-space>
                <n-radio v-for="v in OPT.yesNo" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
        </n-descriptions>
      </div>
    </n-card>

    <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
      <template #header>
        <n-h6 prefix="bar" style="margin: 0;font-size: 18px">月经/婚育史</n-h6>
      </template>
      <div class="info1">
        <n-descriptions style="width: 100%;" label-placement="left" bordered :column="3">
          <n-descriptions-item label="初潮年龄">
            <span v-if="!record.is_edit">{{ record.menarche_age }}</span>
            <n-input v-else v-model:value="record.menarche_age"/>
          </n-descriptions-item>
          <n-descriptions-item label="末次月经时间">
            <span v-if="!record.is_edit">{{ record.last_menstrual_period_date }}</span>
            <n-date-picker v-else v-model:value="record.last_menstrual_period_date" type="date" value-format="yyyy-MM-dd" clearable placeholder="末次月经"/>
          </n-descriptions-item>
          <n-descriptions-item label="经期">
            <span v-if="!record.is_edit">{{ record.menstrual_cycle_duration }}</span>
            <n-radio-group v-else v-model:value="record.menstrual_cycle_duration">
              <n-space>
                <n-radio v-for="v in OPT.menstrual_cycle_duration" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="月经量">
            <span v-if="!record.is_edit">{{ record.menstrual_flow }}</span>
            <n-radio-group v-else v-model:value="record.menstrual_flow">
              <n-space>
                <n-radio v-for="v in OPT.menstrualFlow" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="单次周期(天)">
            <span v-if="!record.is_edit">{{ record.single_menstrual_cycle_days }}</span>
            <n-input v-else v-model:value="record.single_menstrual_cycle_days"/>
          </n-descriptions-item>
          <n-descriptions-item label="痛经情况">
            <span v-if="!record.is_edit">{{ record.dysmenorrhea_condition }}</span>
            <n-radio-group v-else v-model:value="record.dysmenorrhea_condition">
              <n-space>
                <n-radio v-for="v in OPT.dysmenorrhea" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="血块情况">
            <span v-if="!record.is_edit">{{ record.blood_clot_condition }}</span>
            <n-radio-group v-else v-model:value="record.blood_clot_condition">
              <n-space>
                <n-radio v-for="v in OPT.clot" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="婚姻状况">
            <span v-if="!record.is_edit">{{ record.marital_status }}</span>
            <n-radio-group v-else v-model:value="record.marital_status">
              <n-space>
                <n-radio value="未婚">未婚</n-radio>
                <n-radio value="已婚">已婚</n-radio>
                <n-radio value="离异">离异</n-radio>
                <n-radio value="丧偶">丧偶</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="结婚年龄">
            <span v-if="!record.is_edit">{{ record.marriage_age }}</span>
            <n-input v-else v-model:value="record.marriage_age"/>
          </n-descriptions-item>
          <n-descriptions-item label="孕(次)">
            <span v-if="!record.is_edit">{{ record.pregnant_time}}</span>
            <n-input v-else v-model:value="record.pregnant_time"/>
          </n-descriptions-item>
          <n-descriptions-item label="产(次)">
            <span v-if="!record.is_edit">{{ record.delivery_time}}</span>
            <n-input v-else v-model:value="record.delivery_time"/>
          </n-descriptions-item>
          <n-descriptions-item label="初次怀孕年龄">
            <span v-if="!record.is_edit">{{ record.first_pregnancy_age }}</span>
            <n-input v-else v-model:value="record.first_pregnancy_age"/>
          </n-descriptions-item>
          <n-descriptions-item label="初次生产年龄">
            <span v-if="!record.is_edit">{{ record.first_childbirth_age }}</span>
            <n-input v-else v-model:value="record.first_childbirth_age"/>
          </n-descriptions-item>
          <n-descriptions-item label="顺产(次)">
            <span v-if="!record.is_edit">{{ record.vaginal_delivery_count }}</span>
            <n-input v-else v-model:value="record.vaginal_delivery_count"/>
          </n-descriptions-item>
          <n-descriptions-item label="剖腹产(次)">
            <span v-if="!record.is_edit">{{ record.cesarean_section_count }}</span>
            <n-input v-else v-model:value="record.cesarean_section_count"/>
          </n-descriptions-item>
          <n-descriptions-item label="人流(次)">
            <span v-if="!record.is_edit">{{ record.induced_abortion_count }}</span>
            <n-input v-else v-model:value="record.induced_abortion_count"/>
          </n-descriptions-item>
          <n-descriptions-item label="早产(次)">
            <span v-if="!record.is_edit">{{ record.premature_birth_count }}</span>
            <n-input v-else v-model:value="record.premature_birth_count"/>
          </n-descriptions-item>
          <n-descriptions-item label="末次怀孕年龄">
            <span v-if="!record.is_edit">{{ record.last_pregnancy_age }}</span>
            <n-input v-else v-model:value="record.last_pregnancy_age"/>
          </n-descriptions-item>
          <n-descriptions-item label="末次生产年龄">
            <span v-if="!record.is_edit">{{ record.last_childbirth_age }}</span>
            <n-input v-else v-model:value="record.last_childbirth_age"/>
          </n-descriptions-item>
          <n-descriptions-item label="是否备孕">
            <span v-if="!record.is_edit">{{ record.is_preparing_pregnancy ? '是' : '否' }}</span>
            <n-radio-group v-else v-model:value="record.is_preparing_pregnancy">
              <n-space>
                <n-radio :value="1">是</n-radio>
                <n-radio :value="0">否</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="是否哺乳期">
            <span v-if="!record.is_edit">{{ record.is_breastfeeding ? '是' : '否' }}</span>
            <n-radio-group v-else v-model:value="record.is_breastfeeding">
              <n-space>
                <n-radio :value="1">是</n-radio>
                <n-radio :value="0">否</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="避孕方式">
            <span v-if="!record.is_edit">{{ record.contraception_method }}</span>
            <n-radio-group v-else v-model:value="record.contraception_method">
              <n-space>
                <n-radio value="药物避孕">药物避孕</n-radio>
                <n-radio value="工具避孕">工具避孕</n-radio>
                <n-radio value="节育环">节育环</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
        </n-descriptions>
      </div>
    </n-card>

    <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
      <template #header>
        <n-h6 prefix="bar" style="margin: 0;font-size: 18px">生活习惯</n-h6>
      </template>
      <div class="info1">
        <n-descriptions style="width: 100%;" label-placement="left" bordered :column="3">
          <n-descriptions-item label="饮酒">
            <span v-if="!record.is_edit">{{ record.alcohol_consumption }}</span>
            <n-radio-group v-else v-model:value="record.alcohol_consumption">
              <n-space>
                <n-radio v-for="v in OPT.alcohol" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="睡眠">
            <span v-if="!record.is_edit">{{ record.sleep_condition }}</span>
            <n-input v-else v-model:value="record.sleep_condition" placeholder="每日约X小时/入眠困难/多梦/打鼾等"/>
          </n-descriptions-item>
          <n-descriptions-item label="吸烟">
            <span v-if="!record.is_edit">{{ record.smoking_condition }}</span>
            <n-radio-group v-else v-model:value="record.smoking_condition">
              <n-space>
                <n-radio v-for="v in OPT.smoking" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="饮食" :span="2">
            <span v-if="!record.is_edit">{{ record.diet_habit?.join('、') }}</span>
            <n-checkbox-group v-else v-model:value="record.diet_habit">
              <n-space>
                <n-checkbox v-for="v in OPT.diet" :key="v" :value="v">{{ v }}</n-checkbox>
              </n-space>
            </n-checkbox-group>
          </n-descriptions-item>
          <n-descriptions-item label="如厕情况">
            <span v-if="!record.is_edit">{{ record.bowel_movement_condition }}</span>
            <n-radio-group v-else v-model:value="record.bowel_movement_condition">
              <n-space>
                <n-radio v-for="v in OPT.toilet" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="运动频率">
            <span v-if="!record.is_edit">{{ record.exercise_frequency }}</span>
            <n-radio-group v-else v-model:value="record.exercise_frequency">
              <n-space>
                <n-radio v-for="v in OPT.exerciseFreq" :key="v" :value="v">{{ v }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-descriptions-item>
          <n-descriptions-item label="运动方式" :span="2">
            <span v-if="!record.is_edit">{{ record.exercise_methods?.join('、') }}</span>
            <n-checkbox-group v-else v-model:value="record.exercise_methods">
              <n-space>
                <n-checkbox v-for="v in OPT.exerciseMethods" :key="v" :value="v">{{ v }}</n-checkbox>
              </n-space>
            </n-checkbox-group>
          </n-descriptions-item>
        </n-descriptions>
      </div>
    </n-card>

    <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
      <template #header>
        <n-h6 prefix="bar" style="margin: 0;font-size: 18px">病史</n-h6>
      </template>
      <div class="info1">
        <n-descriptions style="width: 100%;" label-placement="left" bordered :column="3">
          <n-descriptions-item label="既往病史" :span="3">
            <span v-if="!record.is_edit">{{ record.past_medical_history }}</span>
            <n-input v-else type="textarea" :autosize="{minRows:2,maxRows:4}" v-model:value="record.past_medical_history"/>
          </n-descriptions-item>
          <n-descriptions-item label="既往手术史" :span="3">
            <span v-if="!record.is_edit">{{ record.past_surgical_history }}</span>
            <n-input v-else type="textarea" :autosize="{minRows:2,maxRows:4}" v-model:value="record.past_surgical_history"/>
          </n-descriptions-item>
          <n-descriptions-item label="过敏史" :span="2">
            <span v-if="!record.is_edit">{{ record.allergy_history }}</span>
            <n-input v-else v-model:value="record.allergy_history" placeholder="过敏原等"/>
          </n-descriptions-item>
          <n-descriptions-item label="过敏药物">
            <span v-if="!record.is_edit">{{ record.allergic_drugs }}</span>
            <n-input v-else v-model:value="record.allergic_drugs"/>
          </n-descriptions-item>
          <n-descriptions-item label="家族病史" :span="3">
            <span v-if="!record.is_edit">{{ record.family_medical_history?.join('、') }}</span>
            <n-checkbox-group v-else v-model:value="record.family_medical_history">
              <n-space>
                <n-checkbox v-for="v in OPT.family" :key="v" :value="v">{{ v }}</n-checkbox>
              </n-space>
            </n-checkbox-group>
          </n-descriptions-item>
        </n-descriptions>
      </div>
    </n-card>

    <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
      <div class="info1">
        <n-descriptions style="width: 100%;" label-placement="right" bordered :column="3">
          <n-descriptions-item label="相关资料">
            <div v-if="!record.is_edit">
              <div v-if="record.files && record.files.length > 0" class="file-list">
                <div v-for="(file, index) in record.files" :key="'saved-'+index" class="file-item">
                  <n-button type="info" text @click="downloadFile(file)" style="margin: 2px;">
                    <TheIcon icon="material-symbols:download" :size="16" class="mr-2"/>
                    {{ getFileName(file) }}
                  </n-button>
                </div>
              </div>
              <span v-else style="color:#999;">暂无文件</span>
            </div>
            <div v-else>
              <div v-if="record.files && record.files.length > 0" class="file-list">
                <div v-for="(file, index) in record.files" :key="'saved2-'+index" class="file-item">
                  <n-button type="info" text @click="downloadFile(file)" style="margin: 2px;">
                    <TheIcon icon="material-symbols:download" :size="16" class="mr-2"/>
                    {{ getFileName(file) }}
                  </n-button>
                  <n-button type="error" text @click="removeSavedFile(index)" style="margin: 2px;" size="small">
                    <TheIcon icon="material-symbols:delete" :size="14"/>
                  </n-button>
                </div>
              </div>
              <div v-if="uploadState.files && uploadState.files.length > 0" class="file-list">
                <div v-for="(file, index) in uploadState.files" :key="'new-'+index" class="file-item">
                  <n-button type="success" text @click="downloadFile(file.url || file.response?.data?.url)" style="margin: 2px;">
                    <TheIcon icon="material-symbols:download" :size="16" class="mr-2"/>
                    {{ file.name || getFileName(file.url || file.response?.data?.url) }}
                  </n-button>
                  <n-button type="error" text @click="removeNewFile(index)" style="margin: 2px;" size="small">
                    <TheIcon icon="material-symbols:delete" :size="14"/>
                  </n-button>
                </div>
              </div>
              <n-upload :headers="{ authorization: uploadState.token }" v-model:file-list="uploadState.files" multiple :action="uploadState.uploadAction" @finish="handleFinish">
                <n-button>上传新文件</n-button>
              </n-upload>
            </div>
          </n-descriptions-item>
        </n-descriptions>
      </div>
    </n-card>

    <div class="tools">
      <n-button v-if="!record.is_edit" type="primary" size="large" style="margin-left:10px" @click="edit_info">
        <TheIcon icon="material-symbols:edit" :size="18" class="mr-5"/>
        编辑
      </n-button>
      <n-button v-if="record.is_edit" type="primary" size="large" style="margin-left:10px" @click="cancel_info">
        <TheIcon icon="material-symbols:cancel" :size="18" class="mr-5"/>
        取消编辑
      </n-button>
      <n-button v-if="record.is_edit" type="primary" size="large" style="margin-left:10px" @click="save_info">
        <TheIcon icon="material-symbols:save-sharp" :size="18" class="mr-5"/>
        保存
      </n-button>
    </div>
  </NScrollbar>
</template>

<style scoped>
.tools{
  position: absolute;
  bottom:0;right:0;
  width:100%;
  height:60px;
  background: #f3f3f3;
  z-index: 99;
  display: flex;
  align-items: center
}
.info1 {
  width: 100%;
  padding: 20px;
  display: flex;
}
</style>


